#!/bin/bash

# Check for correct number of arguments
if [ "$#" -lt 3 ]; then
    echo "Usage: $0 <docx_file> <find_string1>:<replace_string1> <find_string2>:<replace_string2> ..."
    exit 1
fi

local_repos_path=${LOCAL_TOOL_PATH:="/h/devworks/win_file_format_conv"}
unix_local_repos_path=$(cygpath -u "$local_repos_path")

DOCX_FILE="$1"
echo $DOCX_FILE
OUT_FILE="$2"
echo $OUT_FILE
archive_info="$3"

shift
shift
shift

echo "$*"

TEMP_DIR="/tmp/docx_temp_$$" # Unique temporary directory

# Create a temporary directory and unzip the docx file
mkdir -p "$TEMP_DIR"
echo unzip -q "$DOCX_FILE" -d "$TEMP_DIR"
unzip -q "$DOCX_FILE" -d "$TEMP_DIR"

IFS='_' read -r term major course class <<< "$archive_info"

echo $term
echo $major
echo $course
echo $class

term_tmpl="【学期】"
major_tmpl="【专业】"
course_tmpl="【课程】"

# 替换学期

sed -i "s/${term_tmpl}/${term}/g" "$TEMP_DIR/word/document.xml"

# 替换专业

sed -i "s/${major_tmpl}/${major}/g" "$TEMP_DIR/word/document.xml"

# 替换课程名

sed -i "s/${course_tmpl}/${course}/g" "$TEMP_DIR/word/document.xml"

# Perform find and replace in document.xml
# The 'g' flag ensures all occurrences are replaced on each line

for arg in "$@"; do
    # everything up to (but not including) the first ':'
    FIND_STRING=${arg%%:*}
    # everything after the first ':'
    REPLACE_STRING=${arg#*:}

    echo $FIND_STRING " -> " $REPLACE_STRING
    
    sed -i "s/${FIND_STRING}/${REPLACE_STRING}/g" "$TEMP_DIR/word/document.xml"
done

# 替换分数段统计

score_dist_tmpl="【卷面统计】"
score_dist_info=$(cut -f ${SCORE_FIELDS} exam_paper_scores.txt | awk -f ${unix_local_repos_path}/count_number_of_students.awk)

sed -i "s/${score_dist_tmpl}/${score_dist_info}/g" "$TEMP_DIR/word/document.xml"

# Re-zip the modified content into a new docx file
# Ensure to change directory into the temp directory before zipping
out_fullpath=$(realpath "${OUT_FILE}")
(cd "$TEMP_DIR" && zip -qr "$out_fullpath" .)

# Clean up the temporary directory
rm -rf "$TEMP_DIR"

echo "Find and replace completed for '$out_fullpath'."